package com.infomanage.service.hr;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.infomanage.authority.AuthorityBean;
import com.infomanage.bean.FieldBean;
import com.infomanage.bean.PaginationBean;
import com.infomanage.bean.SearchBean;
import com.infomanage.dao.EquipmentDiscardDAO;
import com.infomanage.dao.EquipmentManageDAO;
import com.infomanage.dao.PersonDAO;
import com.infomanage.dao.PersonDegreeInfoDAO;
import com.infomanage.dao.PersonFamilyInfoDAO;
import com.infomanage.dao.PersonResumeInfoDAO;
import com.infomanage.dao.PersonRewardInfoDAO;
import com.infomanage.dao.PersonStudyInfoDAO;
import com.infomanage.enums.RoleType;
import com.infomanage.po.EquipmentManage;
import com.infomanage.po.Person;
import com.infomanage.po.PersonDegreeInfo;
import com.infomanage.po.PersonFamilyInfo;
import com.infomanage.po.PersonResumeInfo;
import com.infomanage.po.PersonRewardInfo;
import com.infomanage.po.PersonStudyInfo;
import com.infomanage.po.User;
import com.infomanage.util.Consts;
import com.infomanage.util.StringUtil;
import com.infomanage.vo.PersonDegreeInfoItem;
import com.infomanage.vo.PersonFamilyInfoItem;
import com.infomanage.vo.PersonItem;
import com.infomanage.vo.PersonResumeInfoItem;
import com.infomanage.vo.PersonRewardInfoItem;
import com.infomanage.vo.PersonStudyInfoItem;
import com.jiuqi.util.ReturnObject;
import com.jiuqi.util.StringUtils;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class PersonManageService {

	private static final int INFO_TYPE_DEGREE = 1;
	private static final int INFO_TYPE_RESUME = 2;
	private static final int INFO_TYPE_FAMILY = 3;
	private static final int INFO_TYPE_REWARD = 4;
	private static final int INFO_TYPE_STUDY = 5;
	public static PersonItem loadPersonBaseInfo(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			String personId = request.getParameter("personId");
			if (StringUtils.isEmpty(personId))
				return null;
			PersonDAO perosnDAO = new PersonDAO();
			return perosnDAO.find(Integer.parseInt(personId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static List<PersonItem> loadPersonList(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			PersonDAO perosnDAO = new PersonDAO();
			List<PersonItem> list = perosnDAO.findAll();
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static ReturnObject savePersonBaseInfo(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String name = request.getParameter("name");
			String sex = request.getParameter("sex");
			String birthDate = request.getParameter("birthDate");
			String nativePlace = request.getParameter("nativePlace");
			String birthPlace = request.getParameter("birthPlace");
			String national = request.getParameter("national");
			String bloodType = request.getParameter("bloodType");
			String workerUser = request.getParameter("workerUseage");
			String joinWay = request.getParameter("joinWay");
			String hukouPlace = request.getParameter("hukouPlace");
			String politicalFace = request.getParameter("politicalFace");
			String deptId = request.getParameter("deptId");
			String deptName = request.getParameter("deptname");
			String techlevel = request.getParameter("techlevel");
			String adminlevel = request.getParameter("adminlevel");
			String workyear = request.getParameter("workyear");
			String joinWorkyear = request.getParameter("joinWorkyear");
			String highestDigree = request.getParameter("highestDegree");
			String position = request.getParameter("position");
			String idNumber = request.getParameter("idNumber");
			String phoneNo = request.getParameter("phoneNo");
			PersonDAO personDAO = new PersonDAO();
			Person person = new Person();
			person.setName(name);
			person.setSex(Integer.parseInt(sex));
			person.setBirthDate(birthDate);
			person.setNativePlace(nativePlace);
			person.setBirthPlace(birthPlace);
			person.setNational(national);
			person.setBloodType(Integer.parseInt(bloodType));
			person.setWorkerUser(workerUser);
			person.setJoinWay(joinWay);
			person.setHukouPlace(hukouPlace);
			person.setPoliticalFace(politicalFace);
			if (deptId != null && !deptId.equals("")) {
				person.setDeptId(Integer.parseInt(deptId));
			}
			person.setDeptName(deptName);
			person.setTechlevel(Integer.parseInt(techlevel));
			person.setAdminlevel(Integer.parseInt(adminlevel));
			person.setWorkyear(workyear);
			person.setJoinWorkyear(joinWorkyear);
			person.setHighestDigree(Integer.parseInt(highestDigree));
			person.setPosition(Integer.parseInt(position));
			person.setIdNumber(idNumber);
			person.setPhoneNo(phoneNo);
			int generateId = personDAO.addAndReturnId(person);
			ret.setErrorMessage(String.valueOf(generateId));
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
			e.printStackTrace();
		}
		return ret;
	}

	public static ReturnObject modifyPersonBaseInfo(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			int personId = Integer.parseInt(request.getParameter("personId"));
			PersonDAO dao = new PersonDAO();
			Person person = dao.find(Person.class, personId);
			String name = request.getParameter("name");
			String sex = request.getParameter("sex");
			String birthDate = request.getParameter("birthDate");
			String nativePlace = request.getParameter("nativePlace");
			String birthPlace = request.getParameter("birthPlace");
			String national = request.getParameter("national");
			String bloodType = request.getParameter("bloodType");
			String workerUser = request.getParameter("workerUseage");
			String joinWay = request.getParameter("joinWay");
			String hukouPlace = request.getParameter("hukouPlace");
			String politicalFace = request.getParameter("politicalFace");
			String deptId = request.getParameter("deptId");
			String deptName = request.getParameter("deptname");
			String techlevel = request.getParameter("techlevel");
			String adminlevel = request.getParameter("adminlevel");
			String workyear = request.getParameter("workyear");
			String joinWorkyear = request.getParameter("joinWorkyear");
			String highestDigree = request.getParameter("highestDegree");
			String position = request.getParameter("position");
			String idNumber = request.getParameter("idNumber");
			String phoneNo = request.getParameter("phoneNo");
			person.setName(name);
			person.setSex(Integer.parseInt(sex));
			person.setBirthDate(birthDate);
			person.setNativePlace(nativePlace);
			person.setBirthPlace(birthPlace);
			person.setNational(national);
			person.setBloodType(Integer.parseInt(bloodType));
			person.setWorkerUser(workerUser);
			person.setJoinWay(joinWay);
			person.setHukouPlace(hukouPlace);
			person.setPoliticalFace(politicalFace);
			if (deptId != null && !deptId.equals("")) {
				person.setDeptId(Integer.parseInt(deptId));
			}
			person.setDeptName(deptName);
			person.setTechlevel(Integer.parseInt(techlevel));
			person.setAdminlevel(Integer.parseInt(adminlevel));
			person.setWorkyear(workyear);
			person.setJoinWorkyear(joinWorkyear);
			person.setHighestDigree(Integer.parseInt(highestDigree));
			person.setPosition(Integer.parseInt(position));
			person.setIdNumber(idNumber);
			person.setPhoneNo(phoneNo);
			dao.modify(person);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(StringUtil.filterIllegalchar(e.getMessage()));
		}
		return ret;
	}
	
	public static List<PersonDegreeInfoItem> loadPersonDegreeInfo(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			String personId= request.getParameter("personId");
			if(StringUtils.isEmpty(personId)) return null;
			PersonDegreeInfoDAO dao = new PersonDegreeInfoDAO();
			PersonDegreeInfo info =  dao.findByPersonId(Integer.parseInt(personId));
			if(info != null){
				List<PersonDegreeInfoItem> items = loadDegree(info.getData());
				return items;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static List<PersonResumeInfoItem> loadPersonResumeInfo(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			String personId= request.getParameter("personId");
			if(StringUtils.isEmpty(personId)) return null;
			PersonResumeInfoDAO dao = new PersonResumeInfoDAO();
			PersonResumeInfo info =  dao.findByPersonId(Integer.parseInt(personId));
			if(info != null){
				List<PersonResumeInfoItem> items = loadResume(info.getData());
				return items;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static List<PersonFamilyInfoItem> loadPersonFamilyInfo(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			String personId= request.getParameter("personId");
			if(StringUtils.isEmpty(personId)) return null;
			PersonFamilyInfoDAO dao = new PersonFamilyInfoDAO();
			PersonFamilyInfo info =  dao.findByPersonId(Integer.parseInt(personId));
			if(info != null){
				List<PersonFamilyInfoItem> items = loadFamily(info.getData());
				return items;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	public static PersonRewardInfo loadPersonRewardInfo(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			String personId= request.getParameter("personId");
			if(StringUtils.isEmpty(personId)) return null;
			PersonRewardInfoDAO dao = new PersonRewardInfoDAO();
			PersonRewardInfo info =  dao.findByPersonId(Integer.parseInt(personId));
			return info;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static List<PersonStudyInfoItem> loadPersonStudyInfo(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			String personId= request.getParameter("personId");
			if(StringUtils.isEmpty(personId)) return null;
			PersonStudyInfoDAO dao = new PersonStudyInfoDAO();
			PersonStudyInfo info =  dao.findByPersonId(Integer.parseInt(personId));
			if(info != null){
				List<PersonStudyInfoItem> items = loadStudy(info.getData());
				return items;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static ReturnObject savePersonDegreeInfo(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			int rows = Integer.parseInt(request.getParameter("rows"));
			String personId = request.getParameter("personId");
			if (personId == null || "".equals(personId)) {
				ret.SetErrored(true);
				ret.setErrorMessage("请先保存基本信息！");
				return ret;
			}
			PersonDegreeInfoDAO dao = new PersonDegreeInfoDAO();
			PersonDegreeInfo oldInfo = dao.findByPersonId(Integer.parseInt(personId));
			if(oldInfo != null){
				dao.removeByPersonDegreeInfo(oldInfo);
			}
			List<String[]> items = new ArrayList<String[]>();
			for (int i = 0; i < rows; i++) {
				String suffix = "_" + i;
				List<String> infos = new ArrayList<String>();
				String entranceTime = request.getParameter("entranceTime"
						+ suffix);
				String graduateTime = request.getParameter("graduateTime"
						+ suffix);
				String graduateSchool = request.getParameter("graduateSchool"
						+ suffix);
				String degree = request.getParameter("degree" + suffix);
				String eduTime = request.getParameter("eduTime" + suffix);
				String eduStyle = request.getParameter("eduStyle" + suffix);
				String jobType = request.getParameter("jobType" + suffix);
				infos.add(entranceTime);
				infos.add(graduateTime);
				infos.add(graduateSchool);
				infos.add(degree);
				infos.add(eduTime);
				infos.add(eduStyle);
				infos.add(jobType);
				items.add(infos.toArray(new String[infos.size()]));
			}
			byte[] data = saveToBytes(items, personId, INFO_TYPE_DEGREE);
			PersonDegreeInfo info = new PersonDegreeInfo();
			info.setPersonId(Integer.parseInt(personId));
			info.setData(data);
			dao.add(info);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
			e.printStackTrace();
		}
		return ret;
	}

	public static ReturnObject savePersonResumeInfo(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			int rows = Integer.parseInt(request.getParameter("rows"));
			String personId = request.getParameter("personId");
			if (personId == null || "".equals(personId)) {
				ret.SetErrored(true);
				ret.setErrorMessage("请先保存基本信息！");
				return ret;
			}
			PersonResumeInfoDAO dao = new PersonResumeInfoDAO();
			PersonResumeInfo oldInfo = dao.findByPersonId(Integer.parseInt(personId));
			if(oldInfo != null){
				dao.removeByPersonResumeInfo(oldInfo);
			}
			List<String[]> items = new ArrayList<String[]>();
			for (int i = 0; i < rows; i++) {
				String suffix = "_" + i;
				List<String> infos = new ArrayList<String>();
				String startTime = request.getParameter("startTime"
						+ suffix);
				String endTime = request.getParameter("endTime"
						+ suffix);
				String company = request.getParameter("company"
						+ suffix);
				String job = request.getParameter("job" + suffix);
				infos.add(startTime);
				infos.add(endTime);
				infos.add(company);
				infos.add(job);
				items.add(infos.toArray(new String[infos.size()]));
			}
			byte[] data = saveToBytes(items, personId, INFO_TYPE_RESUME);
			PersonResumeInfo info = new PersonResumeInfo();
			info.setPersonId(Integer.parseInt(personId));
			info.setData(data);
			dao.add(info);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
			e.printStackTrace();
		}
		return ret;
	}
	
	public static ReturnObject savePersonFamilyInfo(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			int rows = Integer.parseInt(request.getParameter("rows"));
			String personId = request.getParameter("personId");
			if (personId == null || "".equals(personId)) {
				ret.SetErrored(true);
				ret.setErrorMessage("请先保存基本信息！");
				return ret;
			}
			PersonFamilyInfoDAO dao = new PersonFamilyInfoDAO();
			PersonFamilyInfo oldInfo = dao.findByPersonId(Integer.parseInt(personId));
			if(oldInfo != null){
				dao.removeByPersonFamilyInfo(oldInfo);
			}
			List<String[]> items = new ArrayList<String[]>();
			for (int i = 0; i < rows; i++) {
				String suffix = "_" + i;
				List<String> infos = new ArrayList<String>();
				String name = request.getParameter("name"
						+ suffix);
				String relation = request.getParameter("relation"
						+ suffix);
				String birthDay = request.getParameter("birthDay"
						+ suffix);
				String degree = request.getParameter("degree" + suffix);
				String political = request.getParameter("political" + suffix);
				String job = request.getParameter("job" + suffix);
				infos.add(name);
				infos.add(relation);
				infos.add(birthDay);
				infos.add(degree);
				infos.add(political);
				infos.add(job);
				items.add(infos.toArray(new String[infos.size()]));
			}
			byte[] data = saveToBytes(items, personId, INFO_TYPE_FAMILY);
			PersonFamilyInfo info = new PersonFamilyInfo();
			info.setPersonId(Integer.parseInt(personId));
			info.setData(data);
			dao.add(info);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
			e.printStackTrace();
		}
		return ret;
	}
	
	public static ReturnObject savePersonRewardInfo(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String personId = request.getParameter("personId");
			if (personId == null || "".equals(personId)) {
				ret.SetErrored(true);
				ret.setErrorMessage("请先保存基本信息！");
				return ret;
			}
			PersonRewardInfoDAO dao = new PersonRewardInfoDAO();
			PersonRewardInfo oldInfo = dao.findByPersonId(Integer.parseInt(personId));
			if(oldInfo != null){
				dao.removeByPersonRewardInfo(oldInfo);
			}
			String context = request.getParameter("context");
			PersonRewardInfo info = new PersonRewardInfo();
			info.setContext(context);
			info.setPersonId(Integer.parseInt(personId));
			dao.add(info);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
			e.printStackTrace();
		}
		return ret;
	}
	
	public static ReturnObject savePersonStudyInfo(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			int rows = Integer.parseInt(request.getParameter("rows"));
			String personId = request.getParameter("personId");
			if (personId == null || "".equals(personId)) {
				ret.SetErrored(true);
				ret.setErrorMessage("请先保存基本信息！");
				return ret;
			}
			PersonStudyInfoDAO dao = new PersonStudyInfoDAO();
			PersonStudyInfo oldInfo = dao.findByPersonId(Integer.parseInt(personId));
			if(oldInfo != null){
				dao.removeByPersonStudyInfo(oldInfo);
			}
			List<String[]> items = new ArrayList<String[]>();
			for (int i = 0; i < rows; i++) {
				String suffix = "_" + i;
				List<String> infos = new ArrayList<String>();
				String startTime = request.getParameter("startTime"
						+ suffix);
				String endTime = request.getParameter("endTime"
						+ suffix);
				String content = request.getParameter("content"
						+ suffix);
				String specialty = request.getParameter("specialty" + suffix);
				String eduLevel = request.getParameter("eduLevel" + suffix);
				infos.add(startTime);
				infos.add(endTime);
				infos.add(content);
				infos.add(specialty);
				infos.add(eduLevel);
				items.add(infos.toArray(new String[infos.size()]));
			}
			byte[] data = saveToBytes(items, personId, INFO_TYPE_STUDY);
			PersonStudyInfo info = new PersonStudyInfo();
			info.setPersonId(Integer.parseInt(personId));
			info.setData(data);
			dao.add(info);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
			e.printStackTrace();
		}
		return ret;
	}
	
	private static byte[] saveToBytes(List<String[]> list, String personId, int infoType)
			throws Exception {
		if (list == null || list.size() == 0) {
			return "".getBytes();
		} else {
			ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.newDocument();
			switch(infoType){
			case INFO_TYPE_DEGREE:
				saveDegree(doc, list, personId);
				break;
			case INFO_TYPE_RESUME:
				saveResume(doc, list, personId);
				break;
			case INFO_TYPE_FAMILY:
				saveFamily(doc, list, personId);
				break;
			case INFO_TYPE_REWARD:
				saveReward(doc, list, personId);
				break;
			case INFO_TYPE_STUDY:
				saveStudy(doc, list, personId);
				break;
			}
			System.out.println(docToString(doc));
			OutputFormat of = new OutputFormat(doc, "UTF-8", false);
			of.setLineSeparator("\n");
			XMLSerializer xs = new XMLSerializer(out, of);
			xs.serialize(doc);
			return out.toByteArray();
		}
	}

	private static Document initLoad(byte[] bytes) throws Exception{
		if (bytes == null || new String(bytes).equalsIgnoreCase("")) {
			return null;
		} else {
			InputStream in = new ByteArrayInputStream(bytes);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setValidating(false);
			dbf.setIgnoringComments(true);
			dbf.setIgnoringElementContentWhitespace(true);
			DocumentBuilder db = dbf.newDocumentBuilder();
			return db.parse(in);
		}
	}
	private static List<PersonDegreeInfoItem> loadDegree(byte[] bytes)
			throws Exception {
		Document doc = initLoad(bytes);
		List<PersonDegreeInfoItem> infoList = new ArrayList<PersonDegreeInfoItem>();
		Element root = doc.getDocumentElement();
		NodeList infos = root.getElementsByTagName("infoItem");
		if (infos.getLength() > 0) {
			for (int i = 0; i < infos.getLength(); i++) {
				PersonDegreeInfoItem item = new PersonDegreeInfoItem();
				Element info = (Element) infos.item(i);
				item.setDegree(getStrAttribute(info, "degree", ""));
				item.setEduStyle(getStrAttribute(info, "eduStyle", ""));
				item.setEduTime(getStrAttribute(info, "eduTime", ""));
				item.setEntranceTime(getStrAttribute(info, "entranceTime", ""));
				item.setGraduateTime(getStrAttribute(info, "graduateTime", ""));
				item.setGraduateSchool(getStrAttribute(info, "graduateSchool", ""));
				item.setJobType(getStrAttribute(info, "jobType", ""));
				infoList.add(item);
			}
		}
		return infoList;
	}
	private static List<PersonResumeInfoItem> loadResume(byte[] bytes) throws Exception {
		Document doc = initLoad(bytes);
		List<PersonResumeInfoItem> infoList = new ArrayList<PersonResumeInfoItem>();
		Element root = doc.getDocumentElement();
		NodeList infos = root.getElementsByTagName("infoItem");
		if (infos.getLength() > 0) {
			for (int i = 0; i < infos.getLength(); i++) {
				PersonResumeInfoItem item = new PersonResumeInfoItem();
				Element info = (Element) infos.item(i);
				item.setStartTime(getStrAttribute(info, "startTime", ""));
				item.setEndTime(getStrAttribute(info, "endTime", ""));
				item.setCompany(getStrAttribute(info, "company", ""));
				item.setJob(getStrAttribute(info, "job", ""));
				infoList.add(item);
			}
		}
		return infoList;
	}
	private static List<PersonFamilyInfoItem> loadFamily(byte[] bytes) throws Exception {
		Document doc = initLoad(bytes);
		List<PersonFamilyInfoItem> infoList = new ArrayList<PersonFamilyInfoItem>();
		Element root = doc.getDocumentElement();
		NodeList infos = root.getElementsByTagName("infoItem");
		if (infos.getLength() > 0) {
			for (int i = 0; i < infos.getLength(); i++) {
				PersonFamilyInfoItem item = new PersonFamilyInfoItem();
				Element info = (Element) infos.item(i);
				item.setName(getStrAttribute(info, "name", ""));
				item.setRelation(getStrAttribute(info, "relation", ""));
				item.setBirthday(getStrAttribute(info, "birthDay", ""));
				item.setDegree(getStrAttribute(info, "degree", ""));
				item.setPolitical(getStrAttribute(info, "political", ""));
				item.setJob(getStrAttribute(info, "job", ""));
				infoList.add(item);
			}
		}
		return infoList;
	}
	private static List<PersonDegreeInfoItem> loadReward(byte[] bytes) throws Exception {
		Document doc = initLoad(bytes);
		List<PersonDegreeInfoItem> infoList = new ArrayList<PersonDegreeInfoItem>();
		Element root = doc.getDocumentElement();
		NodeList infos = root.getElementsByTagName("infoItem");
		if (infos.getLength() > 0) {
			for (int i = 0; i < infos.getLength(); i++) {
				PersonDegreeInfoItem item = new PersonDegreeInfoItem();
				Element info = (Element) infos.item(i);
				item.setDegree(getStrAttribute(info, "degree", ""));
				item.setEduStyle(getStrAttribute(info, "eduStyle", ""));
				item.setEduTime(getStrAttribute(info, "eduTime", ""));
				item.setEntranceTime(getStrAttribute(info, "entranceTime", ""));
				item.setGraduateTime(getStrAttribute(info, "graduateTime", ""));
				item.setGraduateSchool(getStrAttribute(info, "graduateSchool", ""));
				item.setJobType(getStrAttribute(info, "jobType", ""));
				infoList.add(item);
			}
		}
		return infoList;
	}
	private static List<PersonStudyInfoItem> loadStudy(byte[] bytes) throws Exception {
		Document doc = initLoad(bytes);
		List<PersonStudyInfoItem> infoList = new ArrayList<PersonStudyInfoItem>();
		Element root = doc.getDocumentElement();
		NodeList infos = root.getElementsByTagName("infoItem");
		if (infos.getLength() > 0) {
			for (int i = 0; i < infos.getLength(); i++) {
				PersonStudyInfoItem item = new PersonStudyInfoItem();
				Element info = (Element) infos.item(i);
				item.setStartTime(getStrAttribute(info, "startTime", ""));
				item.setEndTime(getStrAttribute(info, "endTime", ""));
				item.setContent(getStrAttribute(info, "content", ""));
				item.setSpecialty(getStrAttribute(info, "specialty", ""));
				item.setEduLevel(getStrAttribute(info, "eduLevel", ""));
				infoList.add(item);
			}
		}
		return infoList;
	}

	private static void saveDegree(Document doc, List<String[]> list, String personId)
			throws Exception {
		Element root = addElem(doc, doc, "degreeInfo");
		root.setAttribute("personId", personId);
		for (int i = 0; i < list.size(); i++) {
			Element ele = addElem(doc, root, "infoItem");
			String[] atts = list.get(i);
			setStringAttribute(ele, "entranceTime", atts[0]);
			setStringAttribute(ele, "graduateTime", atts[1]);
			setStringAttribute(ele, "graduateSchool", atts[2]);
			setStringAttribute(ele, "degree", atts[3]);
			setStringAttribute(ele, "eduTime", atts[4]);
			setStringAttribute(ele, "eduStyle", atts[5]);
			setStringAttribute(ele, "jobType", atts[6]);
		}
	}
	private static void saveResume(Document doc, List<String[]> list, String personId)
	throws Exception {
		Element root = addElem(doc, doc, "resumeInfo");
		root.setAttribute("personId", personId);
		for (int i = 0; i < list.size(); i++) {
			Element ele = addElem(doc, root, "infoItem");
			String[] atts = list.get(i);
			setStringAttribute(ele, "startTime", atts[0]);
			setStringAttribute(ele, "endTime", atts[1]);
			setStringAttribute(ele, "company", atts[2]);
			setStringAttribute(ele, "job", atts[3]);
		}
	}
	private static void saveFamily(Document doc, List<String[]> list, String personId)
	throws Exception {
		Element root = addElem(doc, doc, "familyInfo");
		root.setAttribute("personId", personId);
		for (int i = 0; i < list.size(); i++) {
			Element ele = addElem(doc, root, "infoItem");
			String[] atts = list.get(i);
			setStringAttribute(ele, "name", atts[0]);
			setStringAttribute(ele, "relation", atts[1]);
			setStringAttribute(ele, "birthDay", atts[2]);
			setStringAttribute(ele, "degree", atts[3]);
			setStringAttribute(ele, "political", atts[4]);
			setStringAttribute(ele, "job", atts[5]);
		}
	}
	
	private static void saveReward(Document doc, List<String[]> list, String personId)
	throws Exception {
		Element root = addElem(doc, doc, "degreeInfo");
		root.setAttribute("personId", personId);
		for (int i = 0; i < list.size(); i++) {
			Element ele = addElem(doc, root, "infoItem");
			String[] atts = list.get(i);
			setStringAttribute(ele, "entranceTime", atts[0]);
			setStringAttribute(ele, "graduateTime", atts[1]);
			setStringAttribute(ele, "graduateSchool", atts[2]);
			setStringAttribute(ele, "degree", atts[3]);
			setStringAttribute(ele, "eduTime", atts[4]);
			setStringAttribute(ele, "eduStyle", atts[5]);
			setStringAttribute(ele, "jobType", atts[6]);
		}
	}
	private static void saveStudy(Document doc, List<String[]> list, String personId)
	throws Exception {
		Element root = addElem(doc, doc, "studyInfo");
		root.setAttribute("personId", personId);
		for (int i = 0; i < list.size(); i++) {
			Element ele = addElem(doc, root, "infoItem");
			String[] atts = list.get(i);
			setStringAttribute(ele, "startTime", atts[0]);
			setStringAttribute(ele, "endTime", atts[1]);
			setStringAttribute(ele, "content", atts[2]);
			setStringAttribute(ele, "specialty", atts[3]);
			setStringAttribute(ele, "eduLevel", atts[4]);
		}
	}

	private static Element addElem(Document doc, Node parent, String name) {
		Element elem = doc.createElement(name);
		parent.appendChild(elem);
		return elem;
	}

	private static void setStringAttribute(Element ele, String name,
			String value) {
		ele.setAttribute(name, value == null ? "" : value);
	}

	private static String getStrAttribute(Element e, String tagName,
			String defValue) {
		Node node = e.getAttributes().getNamedItem(tagName);
		if (node == null) {
			return defValue;
		} else {
			return node.getNodeValue();
		}
	}

	public static String docToString(Document doc) {
		// XML转字符串
		String xmlStr = "";
		try {
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer t = tf.newTransformer();
			t.setOutputProperty("encoding", "UTF-8");
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			t.transform(new DOMSource(doc), new StreamResult(bos));
			xmlStr = bos.toString();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		return xmlStr;
	}

	public static ReturnObject removePersonBaseInfo(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String personId = request.getParameter("personId");
			PersonDAO personDAO = new PersonDAO();
			personDAO.remove(Person.class, Integer.parseInt(personId));
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}

	public static ReturnObject removeBatchPersonBaseInfo(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String batchIds = request.getParameter("batchIds");
			PersonDAO dao = new PersonDAO();
			if(batchIds != null){
				String[] ids = batchIds.split(";");
				for(String id : ids){
					dao.remove(Person.class, Integer.parseInt(id));
				}
			}
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}
	
	public static List<PersonItem> search(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			PersonDAO dao = new PersonDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			//设置分页
			String currPageNum = request.getParameter("currPageNum");
			PaginationBean page = new PaginationBean();
			if(currPageNum == null){
				page.setCurrentPageNum(1);
			}else{
				page.setCurrentPageNum(Integer.parseInt(currPageNum));
				
			}
			searchBean.setPage(page);
			List<PersonItem> list = dao.findByFields(searchBean);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static int getPageCount(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			PersonDAO dao = new PersonDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			return (dao.count(searchBean) + PaginationBean.pageSize - 1)/PaginationBean.pageSize;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 1;
	}
	
	private static SearchBean buildSearchCondition(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws Exception{
		request.setCharacterEncoding("UTF-8");
		String name = request.getParameter("name");
		String sex = request.getParameter("sex");
		String deptId = request.getParameter("deptId");
		String position = request.getParameter("position");
		String birthDate = request.getParameter("birthDate");
		String highestDigree = request.getParameter("highestDigree");
		String adminlevel = request.getParameter("adminlevel");
		String techlevel = request.getParameter("techlevel");
		SearchBean searchBean = new SearchBean();
		if (!StringUtil.isEmpty(name)) {
			FieldBean field = new FieldBean("name", name);
			field.setLike(true);
			searchBean.add(field);
		}
		if(!StringUtil.isEmpty(sex)){
			FieldBean field = new FieldBean("sex", sex);
			searchBean.add(field);
		}
		if(!StringUtil.isEmpty(deptId)){
			FieldBean field = new FieldBean("deptId", deptId);
			searchBean.add(field);
		}
		if(!StringUtil.isEmpty(position)){
			FieldBean field = new FieldBean("position", position);
			searchBean.add(field);
		}
		if (!StringUtil.isEmpty(birthDate)) {
			FieldBean field = new FieldBean("birthDate", birthDate);
			searchBean.add(field);
		}
		if (!StringUtil.isEmpty(highestDigree)) {
			FieldBean field = new FieldBean("highestDigree", highestDigree);
			searchBean.add(field);
		}
		if (!StringUtil.isEmpty(adminlevel)) {
			FieldBean field = new FieldBean("adminlevel", adminlevel);
			searchBean.add(field);
		}
		if (!StringUtil.isEmpty(techlevel)) {
			FieldBean field = new FieldBean("techlevel", techlevel);
			searchBean.add(field);
		}
		
		//设置权限
		User user = (User) request.getSession().getAttribute(Consts.LOGINED_USER);
		if(user != null){
			AuthorityBean authority = new AuthorityBean();
			authority.setRole(RoleType.valueOf(user.getRoleId()));
			authority.setDeptId(user.getAssociatedDept());
			searchBean.setAuthority(authority);
		}
	return searchBean;
}
}
